@echo off
SetLocal

set BASE_DIR=%~dp0\..

set FIXED_FILES=%~dp0\files
set RELEASE_DIR_DST=%~dp0\release
set SRC_RELEASE_DIR_DST=%~dp0\release\source
set BIN_RELEASE_DIR_DST=%~dp0\release\binary
set FOLDER_IN_ZIP_NAME=%~dp0\chalice

set CHALICE_JAR_SRC=%BASE_DIR%\target\scala-2.10\chalice_2.10-1.0.jar
set CHALICE_JAR_DST=%BIN_RELEASE_DIR_DST%\chalice.jar

REM get the current date in a locale-independent way
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined fulldate set fulldate=%%x
set shortdate=%fulldate:~0,4%-%fulldate:~4,2%-%fulldate:~6,2%

set RELEASE_NAME=%~dp0\chalice-%shortdate%.zip

REM compile (if necessary) and package the project
call :STATUS "Compiling (if necessary) and packaging project..."
pushd %BASE_DIR%
call sbt.bat package
popd

call :STATUS "Copying files..."

REM create empty directories for the releases
if exist "%RELEASE_DIR_DST%" rmdir /S /Q "%RELEASE_DIR_DST%"
mkdir "%RELEASE_DIR_DST%"
mkdir "%SRC_RELEASE_DIR_DST%"
mkdir "%BIN_RELEASE_DIR_DST%"

REM copy tests
mkdir "%SRC_RELEASE_DIR_DST%\tests"
xcopy /S /Q "%BASE_DIR%\tests" "%SRC_RELEASE_DIR_DST%\tests"
rmdir /S /Q "%SRC_RELEASE_DIR_DST%\tests\refinements"

REM copy readme
copy "%BASE_DIR%\README.md" "%SRC_RELEASE_DIR_DST%\readme.txt"

REM copy everything from 'source' to 'binary' (everything else is specific to one folder)
xcopy /S /Q "%SRC_RELEASE_DIR_DST%" "%BIN_RELEASE_DIR_DST%"

REM copy chalice JAR
copy "%CHALICE_JAR_SRC%" "%CHALICE_JAR_DST%"

REM copy fixed files from 'files'
copy "%FIXED_FILES%\chalice.bat" "%BIN_RELEASE_DIR_DST%"

REM copy source files
copy "%BASE_DIR%\chalice.bat" "%SRC_RELEASE_DIR_DST%\chalice.bat"
copy "%BASE_DIR%\Chalice.iml" "%SRC_RELEASE_DIR_DST%\Chalice.iml"
copy "%BASE_DIR%\sbt.bat" "%SRC_RELEASE_DIR_DST%\sbt.bat"
copy "%BASE_DIR%\sbt-launch.jar" "%SRC_RELEASE_DIR_DST%\sbt-launch.jar"
copy "%BASE_DIR%\build.sbt" "%SRC_RELEASE_DIR_DST%\build.sbt"
mkdir "%SRC_RELEASE_DIR_DST%\project"
copy "%BASE_DIR%\project\plugins.sbt" "%SRC_RELEASE_DIR_DST%\project\plugins.sbt"
copy "%BASE_DIR%\project\build.properties" "%SRC_RELEASE_DIR_DST%\project\build.properties"
xcopy /I /E /S /Q "%BASE_DIR%\src" "%SRC_RELEASE_DIR_DST%\src"

REM zip
call :STATUS "Zipping release directory as %RELEASE_NAME%..."
timeout 1
del %RELEASE_NAME%
move "%RELEASE_DIR_DST%" "%FOLDER_IN_ZIP_NAME%"
call util/zip.bat "%FOLDER_IN_ZIP_NAME%" "%RELEASE_NAME%"
move "%FOLDER_IN_ZIP_NAME%" "%RELEASE_DIR_DST%"

exit /b 1


REM output some status message
:STATUS
ECHO ---------------------------------------------------------
ECHO %1
ECHO ---------------------------------------------------------
goto :EOF

